package com.atguigu.yygh.hosp.utiles;

import com.atguigu.yygh.common.exception.YyghException;
import com.atguigu.yygh.common.helper.HttpRequestHelper;
import com.atguigu.yygh.common.result.ResultCodeEnum;
import com.atguigu.yygh.common.utils.MD5;
import com.atguigu.yygh.hosp.service.HospitalSetService;
import com.atguigu.yygh.hosp.service.impl.HospitalSetServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;

import javax.annotation.PostConstruct;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Component
public class SignKey {

    @Autowired
    private HospitalSetService  hospitalSetService;

    public static SignKey signKey;

    @PostConstruct
    public void init(){
        signKey = this;
    }


    public static Map<String,Object> checkSignKey(HttpServletRequest request){
        //获取传递过来的医院信息
        Map<String, String[]> requestMap = request.getParameterMap();
        Map<String, Object> paramMap = HttpRequestHelper.switchMap(requestMap);

        //1. 获取医院传递过来的签名
        String hospitalSign = (String) paramMap.get("sign");
        //2. 获取医院编号
        String hoscode = (String) paramMap.get("hoscode");
        //3. 根据医院传递过来的编码,查询数据库,查询签名
        String signKey = SignKey.signKey.hospitalSetService.getSignKey(hoscode);

        //4. 将数据库查询到的签名进行MD5加密
        String signKeyMd5 = MD5.encrypt(signKey);
        //5. 判断签名是否一致
        if (!signKeyMd5.equals(hospitalSign)){
            throw new YyghException(ResultCodeEnum.SIGN_ERROR);
        }
        return paramMap;
    }
}
